#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>


void worker()
{
    int cnt = 5;
    while(cnt--)
    {
        printf("I am child process,my pid is %d,my ppid is %d\n",getpid(),getppid());
        sleep(1);
    }
}
int main()
{
    pid_t id = fork();
    if(id == 0) //子进程
    {
        worker();
        int a = 100;
        a = a/0;
        exit(10);
    }
    else{
        int status;  //获取子进程退出状态，由OS填充
        int num = 0;
        pid_t ret = 0;
        //sleep(10);
        while(ret == 0)  //循环等待，返回值为0代表子进程还未结束，在WNOHANG选项下
        {
            num++;
            sleep(1);
            ret = waitpid(id,&status,WNOHANG);  //WNOHANG表示非阻塞等待
        }
        printf("num = %d\n",num);
        if(ret == id) //返回值为子进程id，表示等待成功
        {
            if(WIFEXITED(status)) //代码跑完正常退出，返回真
            {
                printf("wait child process success,exit code is %d \n", WEXITSTATUS(status));  //获取退出码
            }
            else{  //代码异常退出
                printf("child process quit accept,exit sign is %d\n",(status & 0xff));
            }
        
        }
        else if(ret == -1){   //返回值小于0，等待失败
            printf("wait accept\n");
        }
    }

    return 0;
}
